define(["ol3"], function (ol) {
    "use strict";

    var ImagesLayer = function ImagesLayer(map, options) {
        this.images = [];
        this.images_map = {};
        this.map = map;
        this.projection = options.projection;
        this.direction = options.direction;
        this._addLayers(options);
    };

    ImagesLayer.prototype._addLayers = function (options) {
        if (options.images) {
            if (options.images instanceof ol.source.Image) {
                this.addImagesBySource(options.images);
            } else if (options.images instanceof ol.layer.Image) {
                this.addImagesByLayers(options.images);
            } else {
                this.addImages(options.images);
            }
        }
    };

    ImagesLayer.prototype.addImages = function (options) {

        var sources = options.map(function (option) {
            return new ol.source.ImageTransform({
                url: option.url,
                crossOrigin: '',
                projection: this.projection,
                imageExtent: option.imageExtent,
                targetPolygon: option.targetPolygon,
                direction: this.direction
            });
        }, this);

        this.addImagesBySopurce(sources);
    };

    ImagesLayer.prototype.addImagesBySopurce = function (sources) {
        var layers = sources.map(function (source) {
            return new ol.layer.Image({
                source: source
            });
        });
        this.addImagesByLayers(layers);
    };

    ImagesLayer.prototype.addImagesByLayers = function (layers) {
        for (var i = 0; i < layers.length; i++) {
            var layer = layers[i];
            this.add(layer);
        }
    };

    ImagesLayer.prototype.add = function (image) {
        this.map.addLayer(image);
        var uid = ol.getUid(image);
        this.images.push(image);
        this.images_map[uid] = image;
    };

    ImagesLayer.prototype.del = function (image) {
        this.map.removeLayer(image);
        var uid = ol.getUid(image);
        this.images.push(image);
        for (var i in this.images) {
            if (this.images[i] == image) {
                this.images.splice(i, 1);
            }
        }
        delete this.images_map[uid];
    };

    ImagesLayer.prototype.clear = function () {
        for (var i in this.images) {
            this.map.removeLayer(this.images[i]);
        }
    };

    ImagesLayer.prototype.setVisible = function (visible) {
        for (var i in this.images) {
            this.images[i].setVisible(visible);
        }
    };

    ImagesLayer.prototype.setOpacity = function (opacity) {
        for (var i in this.images) {
            this.images[i].setOpacity(opacity);
        }
    };

    ol.layer.ImagesLayer = ImagesLayer;
});
